package level.editor.control.layer;

import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;

import javax.swing.Icon;
import javax.swing.JPanel;
import level.editor.control.main.Main;
import level.model.Addable;
import level.model.StateLayer;
import level.model.utility.StateHandler;

public class Layer extends JPanel
{
	public Layer(StateLayer layer)
	{
		super(new BorderLayout());
		this.layer = layer;
		setVisible(true);
		setOpaque(false);
		visible = true;
		locked = false;
		image = null;
		ghost = null;
		icon = null;
	}

	public LayerImage getImage()
	{
		return image;
	}

	public void setImage(LayerImage image)
	{
		this.image = image;
	}

	public void setName(String name)
	{
		layer.setName(name);
	}

	public String getName()
	{
		return layer.getName();
	}

	public Integer getLayerNumber()
	{
		return layer.getZOrder();
	}

	public void setVisible(boolean visible)
	{
		this.visible = visible;
	}

	public boolean isVisible()
	{
		return visible;
	}

	public void setLock(boolean lock)
	{
		this.locked = lock;
	}

	public boolean isLocked()
	{
		return locked;
	}

	public void paintFromState()
	{
		LayerPainter.updateImage(this, layer);
	}

	public void addObject(Addable addable)
	{
		StateHandler.add(layer, addable);
		LayerPainter.updateImage(this, layer, addable);
	}

	public void setGhost(Addable addable, Icon icon)
	{
		this.ghost = addable;
		this.icon = icon;
	}

	public Addable select(Point pt)
	{
		// This should be implemented by the appropriate classes
		return null;
	}
	
	public ArrayList<Addable> select(Rectangle rectangle)
	{
		// This should be implemented by the appropriate classes
		return null;
	}

	public void remove(Addable addable)
	{
		// This should be implemented by the appropriate classes
	}
	
	public void debug()
	{
		
	}

	@Override
	public void paintComponent(Graphics gOld)
	{
		setSize(getParent().getSize());

		if (visible)
		{
			Graphics2D g = (Graphics2D) gOld;

			if (image != null)
			{
				if (locked)
					g.setComposite(AlphaComposite.getInstance(
							AlphaComposite.SRC_OVER, 0.5f));

				g.drawImage(image, (int) ((Main) getParent()).getOrigin()
						.getX() + image.getLeft(), (int) ((Main) getParent())
						.getOrigin().getY() + image.getTop(), this);
			}

			if (ghost != null && !locked)
			{
				g.setComposite(AlphaComposite.getInstance(
						AlphaComposite.SRC_OVER, 0.5f));
				LayerPainter.paintGhost(g, ghost, icon,
						((Main) getParent()).getOrigin(), this);

			}
			else if (locked)
			{
				ghost = null;
			}
		}
	}

	protected StateLayer layer;
	protected LayerImage image;
	private boolean locked;
	private boolean visible;
	private Addable ghost;
	private Icon icon;
}
